package com.lsh.ofc.core.service.impl;

import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.dao.MeipiCustomerDAO;
import com.lsh.ofc.core.entity.MeipiCustomer;
import com.lsh.ofc.core.enums.Valid;
import com.lsh.ofc.core.redis.RedisTemplate;
import com.lsh.ofc.core.service.SaasMeipiCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Project Name: lsh-ofc
 *
 * @author peter
 * @date 2019-09-25
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Slf4j
public class SaasMeipiCustomerServiceImpl implements SaasMeipiCustomerService {

    @Autowired
    private MeipiCustomerDAO meipiCustomerDAO;

    @Autowired
    private RedisTemplate redisTemplate;


    @Transactional
    @Override
    public String addSaasMpCust(Integer regionCode, Integer cusType, String custCode, Long venderId) throws BusinessException {
        log.info("SAAS客户开始... 地域编号=" + regionCode);
        long ts = System.currentTimeMillis();
        MeipiCustomer mpCustomer = new MeipiCustomer();
        mpCustomer.setCustName("超市" + ts);
        mpCustomer.setRegionCode(regionCode);
        mpCustomer.setContactName("用户" + ts);
        mpCustomer.setContactPhone("13800000000");
        mpCustomer.setProvince("北京市");
        mpCustomer.setCity("市辖区");
        mpCustomer.setDistrict("海淀区");
        mpCustomer.setAddress("占位地址");
        mpCustomer.setCusType(cusType);
        mpCustomer.setCustZone("BX04");
        mpCustomer.setCustCode(custCode);
        mpCustomer.setValid(Valid.disable.getValue());
        mpCustomer.setVenderId(venderId);
        this.meipiCustomerDAO.insert(mpCustomer);
        this.redisTemplate.rpush(this.getKey4List(regionCode, cusType), custCode);
        log.info("SAAS新增美批客户完成... 地域编号=" + regionCode + "。返回美批客户号=" + custCode);
        return custCode;
    }

    @Transactional
    @Override
    public int count(MeipiCustomer customer) throws BusinessException {
        return this.meipiCustomerDAO.count(customer);
    }

    @Transactional
    @Override
    public MeipiCustomer getMaxMeipiCodeByType(Integer custype) throws BusinessException {
        return this.meipiCustomerDAO.getMaxMeipiCodeByType(custype);
    }

    private String getKey4List(Integer regionCode, Integer custype) throws BusinessException {
        return new StringBuilder(Constants.kEY_MEIPI_CUSTOMER_CODES).append("_").append(regionCode).append("_").append(custype).toString();
    }
}
